import { ref, reactive } from "vue";

interface TableConfig {
  pageSize?: number;
  showSelection?: boolean;
  showPagination?: boolean;
  enableSearch?: boolean;
}

export const useTableHook = (config: TableConfig = {}) => {
  const {
    pageSize = 20,
    showSelection = true,
    showPagination = true,
    enableSearch = true,
  } = config;

  // 基础状态
  const tableRef = ref();
  const loading = ref(false);
  const dataSource = ref<any[]>([]);
  const total = ref(0);
  const currentPage = ref(1);

  // 分页配置
  const pagination = reactive({
    current: currentPage.value,
    pageSize,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) =>
      `共 ${total} 条，第 ${range[0]}-${range[1]} 条`,
    pageSizeOptions: ["10", "20", "50", "100"],
    onChange: (page: number, size: number) => {
      currentPage.value = page;
      pageSize = size;
      loadData();
    },
  });

  // 行选择配置
  const rowSelection = showSelection
    ? reactive({
        selectedRowKeys: [],
        preserveSelectedRowKeys: true,
        onChange: (selectedRowKeys: any[], selectedRows: any[]) => {
          rowSelection.selectedRowKeys = selectedRowKeys;
        },
      })
    : null;

  // 排序配置
  const sorter = reactive({
    field: "",
    order: "",
  });

  // 筛选配置
  const filters = ref<Record<string, any>>({});

  // 搜索配置
  const searchText = ref("");
  const searchField = ref("name");

  // 数据加载方法
  const loadData = async (extraParams = {}) => {
    loading.value = true;
    try {
      const params = {
        page: currentPage.value,
        pageSize: pageSize,
        sortBy: sorter.field || undefined,
        sortOrder: sorter.order === "ascend" ? "asc" : "desc" || undefined,
        ...filters.value,
        search: searchText.value || undefined,
        ...extraParams,
      };

      // 这里应该调用实际的API
      // const response = await api.xxx.list(params);
      // dataSource.value = response.data;
      // total.value = response.pagination.total;
      // pagination.total = response.pagination.total;

      console.log("Loading data with params:", params);
    } catch (error) {
      console.error("加载数据失败:", error);
      ElMessage.error("加载数据失败");
    } finally {
      loading.value = false;
    }
  };

  // 表格变化处理
  const handleTableChange = (pag: any, filters: any, sorter: any) => {
    currentPage.value = pag.current;
    pageSize = pag.pageSize;

    // 更新排序
    sorter.field = sorter.field;
    sorter.order = sorter.order;

    // 更新筛选
    filters.value = filters;

    loadData();
  };

  // 搜索处理
  const handleSearch = (value: string) => {
    searchText.value = value;
    currentPage.value = 1; // 搜索时重置到第一页
    loadData();
  };

  // 重置搜索
  const handleReset = () => {
    searchText.value = "";
    filters.value = {};
    currentPage.value = 1;
    loadData();
  };

  // 清空选择
  const clearSelectedRowKeys = () => {
    if (rowSelection) {
      rowSelection.selectedRowKeys = [];
    }
  };

  // 刷新数据
  const reload = () => {
    loadData();
  };

  // 初始化数据
  const init = () => {
    loadData();
  };

  return {
    // 状态
    tableRef,
    loading,
    dataSource,
    total,
    currentPage,

    // 配置
    pagination,
    rowSelection,
    sorter,
    filters,

    // 搜索
    searchText,
    searchField,

    // 方法
    loadData,
    handleTableChange,
    handleSearch,
    handleReset,
    clearSelectedRowKeys,
    reload,
    init,
  };
};
